package nju.bishe.weibo.task;

import nju.bishe.weibo.TwitterApplication;
import nju.bishe.weibo.data.Tweet;
import nju.bishe.weibo.data.db.StatusTable;
import nju.bishe.weibo.ui.base.BaseActivity;
import weibo4andriod.WeiboException;
import android.util.Log;

public class TweetCommonTask {
	public static class DeleteTask extends GenericTask {
		public static final String TAG = "DeleteTask";

		private BaseActivity activity;

		public DeleteTask(BaseActivity activity) {
			this.activity = activity;
		}

		@Override
		protected TaskResult _doInBackground(TaskParams... params) {
			TaskParams param = params[0];
			try {
				String id = param.getString("id");
				weibo4andriod.Status status = null;

				status = activity.getApi().destroyStatus(Long.parseLong(id));

				// 对所有相关表的对应消息都进行删除（如果存在的话）
				activity.getDb().deleteTweet("" + status.getId(), "", -1);
			} catch (WeiboException e) {
				Log.e(TAG, e.getMessage(), e);
				return TaskResult.IO_ERROR;
			}

			return TaskResult.OK;

		}

	}

	public static class FavoriteTask extends GenericTask {
		private static final String TAG = "FavoriteTask";

		private BaseActivity activity;

		public static final String TYPE_ADD = "add";
		public static final String TYPE_DEL = "del";

		private String type;

		public String getType() {
			return type;
		}

		public FavoriteTask(BaseActivity activity) {
			this.activity = activity;
		}

		@Override
		protected TaskResult _doInBackground(TaskParams... params) {
			TaskParams param = params[0];
			try {
				String action = param.getString("action");
				String id = param.getString("id");

				weibo4andriod.Status status = null;
				if (action.equals(TYPE_ADD)) {
					status = activity.getApi().createFavorite(
							Long.parseLong(id));
					activity.getDb().setFavorited(id, "true");
					type = TYPE_ADD;
				} else {
					status = activity.getApi().destroyFavorite(
							Long.parseLong(id));
					activity.getDb().setFavorited(id, "false");
					type = TYPE_DEL;
				}

				Tweet tweet = Tweet.create(status);

				if (action.equals(TYPE_DEL)) {
					activity.getDb().deleteTweet(tweet.id,
							TwitterApplication.getMyselfId(),
							StatusTable.TYPE_FAVORITE);
				}
			} catch (WeiboException e) {
				Log.e(TAG, e.getMessage(), e);
				return TaskResult.IO_ERROR;
			}

			return TaskResult.OK;
		}
	}

}
